/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.geolocation_service;

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.hiddenequity.utils.XMLUtils;

public class GeoLocationResponseParser {
	
	
	Document _XMLDocument;


	/*
	 * Constructor
	 */
	public GeoLocationResponseParser(String XMLData){
		try {
			_XMLDocument = XMLUtils.XMLStringToDoc(XMLData);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}//Constructors
	
	
	
	/*
	 * Check response for errors
	 */
	public String checkForErrors(){
		String error = null;
		try {
	        
	        NodeList faultstring = _XMLDocument.getElementsByTagName("faultstring");
	        error =  XMLUtils.getCharacterDataFromElement((Element) faultstring.item(0));
	        
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return error;
	}//checkForErrors
	
	
	/*
	 * Check if geo data avalable
	 */
	public boolean isGeoDataReceived(){
		boolean result = true;
		try {
	        
	        NodeList geoLocationTypeNode = _XMLDocument.getElementsByTagName("GeoLocation.Type");
	        String geoLocationType =  XMLUtils.getCharacterDataFromElement((Element) geoLocationTypeNode.item(0));
	        
	        if(!geoLocationType.equals("GeoLocation")){
	        	result = false;
	        }
	        
	    } catch (Exception e) {
	    	e.printStackTrace();
	    	result = false;
	    }
		return result;
	}
	
	
	
	/*
	 * Parese geo location data
	 */
	public Map<String, String> getGeoLocationData(){
		Map<String, String> temp = new HashMap<String, String>();
		
		try {

			NodeList nodes = _XMLDocument.getElementsByTagName("rval");
			
	        for (int i = 0; i < nodes.getLength(); i++) {
                //fill up hush map for list population
 
	        	Element element = (Element) nodes.item(i);

	        	NodeList encodedLocation = element.getElementsByTagName("encodedLocation");
	        	temp.put("encodedLocation", XMLUtils.getCharacterDataFromElement((Element) encodedLocation.item(0)));
	        	
	        	NodeList latitudeInMicroDegrees = element.getElementsByTagName("latitudeInMicroDegrees");
	        	temp.put("latitudeInMicroDegrees", XMLUtils.getCharacterDataFromElement((Element) latitudeInMicroDegrees.item(0)));
	        	
	        	NodeList longitudeInMicroDegrees = element.getElementsByTagName("longitudeInMicroDegrees");
	        	temp.put("longitudeInMicroDegrees", XMLUtils.getCharacterDataFromElement((Element) longitudeInMicroDegrees.item(0)));	 
	        }

	    } catch (Exception e) {
	    	e.printStackTrace();
	    }

		return temp;
	}//getGeoLocationData
	
}
